import { authInfoApi, logoutApi } from '@/api/login'
import { staticUrl } from '@/utils/frame'

import Cache from '@/plugins/cache'

const user = {
  namespaced: true,
  state: {
    token: Cache.local().get('vv__login_token', ''),
    id: '',
    name: '',
    avatar: require('@/assets/images/profile.jpg'),
    roles: [],
    permissions: [],
    user: null
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      if (token) {
        Cache.local().set('vv__login_token', token)
      } else {
        Cache.local().clear('vv__login_token')
      }
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, token) {
      return new Promise((resolve, reject) => {
        if (token) {
          commit('SET_TOKEN', token)
          resolve()
        } else {
          reject('登录标识缺失')
        }
      })
    },

    // 获取用户信息
    AuthInfo({ commit }) {
      return new Promise((resolve, reject) => {
        authInfoApi()
          .then(data => {
            const user = data.user
            const avatar = user.avatar ? staticUrl(user.avatar) : require('@/assets/images/profile.jpg')
            if (data.roles && data.roles.length) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', data.roles)
              commit('SET_PERMISSIONS', data.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_ID', user.id)
            commit('SET_NAME', user.nick_name)
            commit('SET_AVATAR', avatar)
            commit('SET_USER', user)
            resolve(data)
          })
          .catch(error => {
            reject(error.msg || '获取用户信息失败')
          })
      })
    },
    // 过期清除
    LogClear({ commit, state }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        resolve()
      })
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise(resolve => {
        logoutApi().finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          resolve()
        })
      })
    }
  }
}

export default user
